package com.cskaoyan.controller.wx;

import com.cskaoyan.bean.Address;
import com.cskaoyan.bean.BasePageData;
import com.cskaoyan.bean.BaseParam;
import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.service.AddressService;
import com.cskaoyan.service.UserService;
import com.cskaoyan.utils.CommonUtil;
import com.cskaoyan.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("wx/address")
public class AddressController {
    @Autowired
    AddressService addressService;

    @RequestMapping("list")
    public BaseRespVo addressList() {
        //需要調整得到用戶信息的token
        Integer userId = CommonUtil.getUserId();
        BasePageData basePageData = addressService.addressQueryByName(userId);
        return BaseRespVo.ok(basePageData);
    }

    @RequestMapping("detail")
    public BaseRespVo detail( Integer id) {

        Address address = addressService.addressQueryById(id);
        return BaseRespVo.ok(address);
    }

    @RequestMapping("save")
    public BaseRespVo save(@RequestBody Address address) {
        //需要調整得到用戶信息的token
        if(CommonUtil.isNull(address.getAddressDetail()))return BaseRespVo.fail(401,"地址详情");
        //手机号判断
        String tel = address.getTel();
        if (!tel.matches(Constant.PHONE)) {
            return BaseRespVo.fail(401,"手机号格式不对");
        }

        address.setUpdateTime(CommonUtil.nowTime());
        Integer id = address.getId();
        if (id == 0) {
            address.setAddTime(CommonUtil.nowTime());
            addressService.createAddress(address);
            return BaseRespVo.ok(address.getId());
        } else {
            addressService.updateAddress(address);
            return BaseRespVo.ok(id);
        }

    }

    @RequestMapping("delete")
    public BaseRespVo delete(@RequestBody Map map) {
        Integer id = (Integer) map.get("id");
        addressService.deleteAddress(id);
        return BaseRespVo.ok();
    }
}
